<template>
  <div>
    <croppa
      v-model="croppa"
      :width="width"
      :height="height"
      placeholder="upload"
      canvas-color="transparent"
      :placeholder-font-size="16"
      :show-remove-button="true"
      :show-loading="true"
      :remove-button-size="18"
      :quality="1"
      :prevent-white-space="true"
      :zoom-speed="10"
      :reverse-scroll-to-zoom="true"
      initial-size="natural"
      initial-position="center"
      :initial-image="initialImage"
    ></croppa>
  </div>
</template>
<script>
import "vue-croppa/dist/vue-croppa.css";
export default {
  props: {
    width: {
      type: Number,
      default: () => 200
    },
    height: {
      type: Number,
      default: () => 200
    }
  },
  name: "about",
  data() {
    return {
      name: "",
      croppa: {},
      dataUrl: "",
      initialImage: null,
      fileDownloadUri: ""
    };
  },
  computed: {
    user() {
      return this.$store.state.authentication.user;
    },
    users() {
      return this.$store.state.users.all;
    }
  },
  created() {
    this.$store.dispatch("users/getAll");
  },
  mounted() {
    this.gerUrl("http://localhost/auth/download/admin/avator.png");
  },
  methods: {
    output(name) {
      localStorage.setItem(name, this.dataUrl);
    },
    gerUrl(fileDownloadUri) {
      let image = new Image();
      // Notice: it's necessary to set "crossorigin" attribute before "src" attribute.
      image.setAttribute("crossorigin", "anonymous");
      image.src = `${fileDownloadUri}/base64`;
      this.initialImage = image;
      this.croppa.refresh();
    },
    download(name, type, compressionRate) {
      const _self = this;
      this.croppa.generateBlob(
        blob => {
          // 将图片上传到服务器.
          var formdata = new FormData();
          formdata.append("file", blob, name + ".png");
          console.log(formdata);
          axios({
            url: `http://${process.env.VUE_APP_BACKEND_URL}/auth/upload`,
            method: "post",
            data: formdata,
            headers: {
              "Content-Type": "multipart/form-data",
              Authorization: `Bearer ${localStorage.getItem("auth-token")}`
            }
          }).then(response => {
            console.log("发送成功");
            if (response.status == 200) {
              console.log(response.data.fileDownloadUri);
              localStorage.removeItem(name);
              alert("上传成功");
            } else {
            }
          });
        },
        type,
        compressionRate
      );
    }
  }
};
</script>
